package com.shanyin.framework.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/***
 ** @category 请用一句话来描述其用途...
 ** @author qing.yunhui
 ** @email: 280672161@qq.com
 ** @createTime: 2018年5月24日上午11:13:49
 **/
public class BeanUtil {

	/**
	 * 遍历对象的属性，将非空属性的名称和值加入map中
	 * @param object
	 * @param map
	 */
	public static Map<String, Object> pojoToMap(Object object) {
		Map<String, Object> tmp = new HashMap<String, Object>();
		if (object == null) {
			return tmp;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		Field[] flds = object.getClass().getDeclaredFields();
		for (Field f : flds) {
			map.put(f.getName(), null);
		}
		Class<?> cls = object.getClass().getSuperclass();
		while (cls != Object.class) {
			Field[] fldz = cls.getDeclaredFields();
			for (Field f : fldz) {
				if (!map.containsKey(f.getName())) {
					map.put(f.getName(), null);
				}
			}
			cls = cls.getSuperclass();
		}
		Set<String> keySet = map.keySet();
		Iterator<String> it = keySet.iterator();
		while (it.hasNext()) {
			String key = it.next();
			String methodName = "get" + StringUtil.firstLetterConvert(key, true);
			try {
				Method m = object.getClass().getMethod(methodName);
				// 调用getter方法获取属性值
				Object value = (Object) m.invoke(object);
				if (StringUtil.isNotEmptys(value)) {
					tmp.put(key, value);
				}
			} catch (SecurityException e) {
			} catch (NoSuchMethodException e) {
			} catch (IllegalArgumentException e) {
			} catch (IllegalAccessException e) {
			} catch (InvocationTargetException e) {
			}
		}
		return tmp;
	}
	
	/**
	 * 遍历对象非空(包括空null及"")属性，copy到map中.
	 * @param object
	 * @return Map<String,Object> 
	 * **/
	public static Map<String,Object> clazToMap(Object object){
		Map<String,Object> map=new HashMap<String,Object>();
		if(null==object) return map;
		Field[] fields=object.getClass().getDeclaredFields();
		for(Field field:fields){
			try {
				//这里过滤掉静态字段、通常entity都实现了序列化！
				int modifiers=field.getModifiers();
				if(Modifier.isStatic(modifiers))continue;
				String name=field.getName();
				Method method=null;
				name=StringUtil.firstLetterConvert(name, true);
				method=object.getClass().getMethod("get"+name);
				Object value=method.invoke(object, new Object[]{});
				if(StringUtil.isNotEmptys(value)){
					if(!map.containsKey(field.getName())){
						map.put(field.getName(),value);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
		return map;
	}
	
}
